﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Transactions;
using Zebra.Utility;

namespace Zebra.DataAccess
{
    //TODO Make this file become utility.

    public class DatabaseUpdate
    {
        private string databaseUpdatePath = Environment.CurrentDirectory + "\\AlterDatabaseScripts";
        private string[] sqlFiles = null;

        public DatabaseUpdate()
        {
            Initialize();
        }
        public DatabaseUpdate(string path)
        {
            databaseUpdatePath = path;
            Initialize();
        }
        private void Initialize()
        {
            sqlFiles = Directory.GetFiles(databaseUpdatePath, "*.sql");
        }

        /// <summary>
        /// This is to run the .sql scripts in the AlterDatabaseScripts folder.
        /// Runtime update the database when system startup.
        /// </summary>
        /// <returns></returns>
        public bool Run()
        {
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    ZebraDataContext db = new ZebraDataContext();

                    if (sqlFiles.Count() == 0) return false; //Return if no database update and no need to run CleanUP()
                    foreach (string s in sqlFiles)
                    {
                        string script = File.ReadAllText(s);
                        if (script.Length > 0)
                            db.ExecuteCommand(script);
                    }

                    ts.Complete();
                    return true;
                }
                catch (Exception ex)
                {
                    Logger.Error(typeof(DatabaseUpdate), ex.ToString());
                    Console.WriteLine(ex);
                    return false;
                }
            }
        }

        public bool CleanUp()
        {
            try
            {
                foreach (string s in sqlFiles)
                {
                    File.Delete(s);
                }
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(typeof(DatabaseUpdate), ex.ToString());
                return false;
            }
        }
    }
}
